import * as requestPromise from 'request-promise-native'
let request = requestPromise.defaults({ json: true })
import * as config from './../../config.js';
import { toCamel } from './../utility'

interface ISection { id: number, name: string }

let sectionMap: { [index: string]: ISection } = {};//key-value 区间名称-区间的id

const Seperator = "～";
/** 从顺凯那边把项目拉过来 */
export function fetchLineFromRemoteAsync(lineName: string) {
    return request({ url: `${config.skyUrl}/GetDeclareItemListByList?MetroLineName=${encodeURIComponent(lineName)}` })
        .then(res => {
            while (typeof res === 'string') res = JSON.parse(res);
            return res;
        }, err => null).then(res => {
            if (res && res.lines && res.lines.length) {
                return toCamel(res.lines[0]);
            } else {
                return { "city": "上海", "lineId": 1, "name": lineName, "sections": [] };
            }
        }).then(line => {
            line.sections.forEach(section => {
                //将string的url替换成array
                section.projects.forEach(prj => {
                    if (!prj.filePath || !prj.filePath.length) return;
                    let imageList = prj.filePath.split(',')
                    imageList.forEach((url, index) => {
                        if (!index) return;
                        imageList[index] = 'http://120.25.160.53/skxs_files/' + url;
                    })
                    delete prj.filePath;
                    prj.imageList = imageList;
                })
                /** @todo */
                //顺凯用的是百度坐标系，需要转换成火星坐标系
            })
            return line;
        });
}

/** 从缓存，或者从远程拉取section */
export async function getSectionAsync(sectionName: string): Promise<ISection> {
    let cache = sectionMap[sectionName];
    if (cache) return cache;
    let stations = sectionName.split(Seperator);
    if (stations.length !== 2) return null;
    let url = `${config.apiUrl}/section/query`
    let section: ISection = await request({ url, qs: { station1: stations[0], station2: stations[1] } }).then(res => res, err => null);
    if (!section) return null;
    return section;
}

export async function uploadToMetroProjects(recordItem) {
    let url = `${config.apiUrl}/Inspect/Record`;
    let ret = await request({
        method: 'post',
        url,
        json: recordItem
    }).then(res => res, err => err);
}